package com.example.blue;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;

import org.example.DTO.AlloutDTO;
import org.example.DTO.BiasDTO;
import org.example.DTO.DuizhioutDTO;
import org.example.DataProcessor;
import org.example.VO.AccGyroBiasVO;
import org.example.VO.DuizhiBiasVO;
import org.example.VO.DuizhioutVO;
import org.example.VO.MagBiasVO;
import org.example.VO.SensorDataVO;
import org.example.result.FeaResult;
import org.example.result.FileResult;
import org.example.result.ZhenChanResult;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

public class CombinedDataProcessor {
    private static DataProcessor dataProcessor = new DataProcessor();

    private static DecimalFormat df = new DecimalFormat("0.################");

    public ProcessedData rawData(byte[] data) {
        // 当功能1被激活时，输出值1
        return new ProcessedData(utils.bytesToHex(data));
    }

    public ProcessedData rawout(byte[] data) {
        String rawstr = utils.bytesToHex(data);
        List<SensorDataVO> res = dataProcessor.rawout(rawstr);
        StringBuilder stringBuilder = new StringBuilder();

        for(SensorDataVO vo : res){
            double[] rawout = vo.getRawout();
            for(double out:rawout){
                stringBuilder.append(df.format(out) + " ");
            }
        }
        return new ProcessedData(stringBuilder.toString(), "rawout");
    }

    public ProcessedData processFunction3(byte[] data) {
        // 当功能3被激活时，输出值3
        return new ProcessedData("3");
    }
    public double calacc(SensorDataVO vo){
        double g=9.7936;
        double[] acccla = vo.getAcccla();
        double sum = 0;
        for(int i = 1;i<4 ;i++){
            sum += acccla[i]*acccla[i];
        }
        double accsum = Math.sqrt(sum) - g;
        return accsum;
    }
    public ProcessedData allout(byte[] data, String accbiasfile, String magbiasfile, int temp) throws IOException {
        String rawstr = utils.bytesToHex(data);
        String AccGyroBiasFilepath = accbiasfile;
        String MagFilepath = magbiasfile;
        AlloutDTO dto = new AlloutDTO(rawstr, AccGyroBiasFilepath, MagFilepath);
        List<SensorDataVO> res = dataProcessor.allout(dto);

        StringBuilder stringBuilder = new StringBuilder();
        StringBuffer angleStr = new StringBuffer();
        StringBuffer accStr = new StringBuffer();

        if(temp == 1){
            for(SensorDataVO vo : res){
                double[] rawout = vo.getRawout();
                double sum = rawout[0]*rawout[0]+rawout[1]*rawout[1]+rawout[2]*rawout[2];
                //System.out.println("testsum: -------------" + sum);
                for(double out:rawout){
                    stringBuilder.append(df.format(out) + " ");
                }
            }
            for(SensorDataVO vo : res){
                double[] qua = vo.getQua();
                for(double out:qua){
                    stringBuilder.append(df.format(out) + " ");
                }
            }

            for(SensorDataVO vo : res){
                double[] angle = vo.getAngle();
                for(double out:angle){
                    angleStr.append(df.format(out) + " ");
                }
            }
            for(SensorDataVO vo : res){
                accStr.append(df.format(calacc(vo))+" ");
            }
        }
        else{
            SensorDataVO vo0 = res.get(0);
            SensorDataVO vo1 = res.get(1);
            SensorDataVO vo2 = res.get(2);
            SensorDataVO vo3 = res.get(3);
            SensorDataVO vo4 = res.get(4);
            SensorDataVO vo5 = res.get(5);

            stringBuilder.append(doutostr(vo0.getRawout())+doutostr(vo5.getRawout())+doutostr(vo4.getRawout())+doutostr(vo3.getRawout())+doutostr(vo2.getRawout())+doutostr(vo1.getRawout())+doutostr(vo0.getQua())+doutostr(vo5.getQua())+doutostr(vo4.getQua())+doutostr(vo3.getQua())+doutostr(vo2.getQua())+doutostr(vo1.getQua()));
            angleStr.append(doutostr(vo0.getAngle())+doutostr(vo5.getAngle())+doutostr(vo4.getAngle())+doutostr(vo3.getAngle())+doutostr(vo2.getAngle())+doutostr(vo1.getAngle()));
            accStr.append(df.format(calacc(vo0)) + " "+df.format(calacc(vo5)) + " "+df.format(calacc(vo4)) + " "+df.format(calacc(vo3)) + " "+df.format(calacc(vo2)) + " "+df.format(calacc(vo1)));
        }
        System.out.println("testaaaa accStr:-----:"+accStr);
        return new ProcessedData(stringBuilder.toString(), angleStr.toString(), accStr.toString(), "allout");
    }
    private String doutostr(double[] in){
        StringBuilder res = new StringBuilder();
        for(double out: in){
            res.append(out+" ");
        }
        return res.toString();
    }
    public ProcessedData magbias(String magfile) throws IOException {
        String filepath = magfile;
        BiasDTO dto = new BiasDTO(filepath);
        List<MagBiasVO> res = dataProcessor.MagBias(dto);
        StringBuilder stringBuilder = new StringBuilder();
        for(MagBiasVO vo:res){
            stringBuilder.append(df.format(vo.getMagXBias())+'\n'+ df.format(vo.getMagYBias())+'\n'+df.format(vo.getMagZBias())+'\n'+df.format(vo.getXS())+'\n'+df.format(vo.getYS())+'\n'+df.format(vo.getZS())+'\n');
        }
        return new ProcessedData(stringBuilder.toString(), "magbias");
    }
    public ProcessedData accgyrobias(String accgyrofile) throws IOException {
        String filepath = accgyrofile;
        BiasDTO dto = new BiasDTO(filepath);
        AccGyroBiasVO res = dataProcessor.AccGyroBias(dto);
        StringBuilder stringBuilder = new StringBuilder();
        double[] resdouble = res.getBias();
        for(double e:resdouble){
            stringBuilder.append(df.format(e)+"\n");
        }
        return new ProcessedData(stringBuilder.toString(), "accgyrobias");
    }

    public double[] duizhibias(String duizhibiasfile) throws IOException {
        String filepath = duizhibiasfile;
        BiasDTO dto = new BiasDTO(filepath);
        DuizhiBiasVO res = dataProcessor.duizhiBias(dto);
        double[] qs2f = res.getQS2F();
        return qs2f;
    }

    public ProcessedData duizhiout(byte[] data, String accbiasfile, String magbiasfile, double[] qs2F,int temp) throws IOException {
        String rawstr = utils.bytesToHex(data);
        String AccGyroBiasFilepath = accbiasfile;
        String MagFilepath = magbiasfile;

        DuizhioutDTO dto = new DuizhioutDTO(rawstr, AccGyroBiasFilepath, MagFilepath, qs2F, temp);
        DuizhioutVO res = dataProcessor.duizhiout(dto);
        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder angleout = new StringBuilder();
        for(double out:res.getDuizhiout()){
            stringBuilder.append(df.format(out) + " ");
        }
        for(double out:res.getAngle()){
            angleout.append(df.format(Math.toDegrees(out)) + " ");
        }
        return new ProcessedData(stringBuilder.toString(), angleout.toString(), "duizhiout");
    }

    public ProcessedData duizhi(String duizhioutfile, String modelfile, int temp) throws Exception {
        System.out.println("ffffffffffffffffffDduizhi:"+temp);

        String fileabsolutePath = duizhioutfile;
        String matabsolutePath = modelfile;
        System.out.println("fileabsolutePath"+fileabsolutePath);
        System.out.println("matabsolutePath:"+matabsolutePath);
        FileResult fileResult = dataProcessor.loaddata(fileabsolutePath);

        Python py = Python.getInstance();
        // 调用 Python 文件中的函数，例如 'myscript.py' 中的 'run' 函数
        PyObject pyModule = py.getModule("test");
        PyObject pyresult = pyModule.callAttr(
                "al_TH_PHI_w",
                fileResult.w_T,
                100,
                temp,
                fileResult.ZYX_X,
                fileResult.ZYX_Y,
                fileResult.ZYX_Z);
        PyObject feaObj = pyresult.asList().get(0);        // numpy array
        PyObject nameTableObj = pyresult.asList().get(1);  // list of strings
// 2. 转为 double[]（fea）
        int feaLen = feaObj.asList().size();
        double[] fea = new double[feaLen];
        for (int i = 0; i < feaLen; i++) {
            fea[i] = feaObj.asList().get(i).toDouble();
        }
        List<PyObject> nameList = nameTableObj.asList();
        String[] nameTable = new String[nameList.size()];
        for (int i = 0; i < nameList.size(); i++) {
            nameTable[i] = nameList.get(i).toString();
        }

        FeaResult feaResult= dataProcessor.feacal(fea, nameTable, temp, matabsolutePath);
        return new ProcessedData("success", feaResult, "duizhiResult");
    }

    public ProcessedData zhenchan(String filepath1, String filepath2, String filepath3, String filepath4) {
        ZhenChanResult res = new ZhenChanResult();
        ZhenChan zc = new ZhenChan();
        try {
            res = zc.dataprocess(filepath1, filepath2, filepath3, filepath4);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        double[] RTDisFea = {4.0000, 3.8974, 7.8125};
//        double[] PDisFea = {3.0000, 1.3188, 3.1250};
//        double[] PTDisFea = {6.0000, 1.2729, 3.1250};
//        double[] PTTDisFea = {6.0000, 1.0794, 4.6875};
//        int RTScore = 0;
//        int PScore = 0;
//        int PTScore = 1;
//        int PTTScore = 1;
//        int pred1ctLabe1 = 1;
//        res.setPDisFea(PDisFea);
//        res.setPredictLabel(pred1ctLabe1);
//        res.setPScore(PScore);
//        res.setPTScore(PTScore);
//        res.setPTDisFea(PTDisFea);
//        res.setRTScore(RTScore);
//        res.setRTDisFea(RTDisFea);
//        res.setPTTDisFea(PTTDisFea);
//        res.setPTTScore(PTTScore);
        return new ProcessedData("success", res, "zhenchanResult");
    }
}
